<template>
  <div class="chart-container">
    <div v-if="currentPageData" ref="chart" style="width: 100%; height: 400px; margin-bottom: 20px;"></div>
    <div class="pagination">
      <span>当前页: {{ currentPage + 1 }} / {{ totalPages }}</span>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import http from '@/http';

export default {
  name: 'HotSalesChart',
  data() {
    return {
      myChart: null,
      chartData: [],
      chartDataGroups: [],
      currentPage: 0,
      itemsPerPage: 5
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.chartData.length / this.itemsPerPage);
    },
    currentPageData() {
      const start = this.currentPage * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.chartData.slice(start, end);
    }
  },
  mounted() {
    this.fetchData();
    window.addEventListener('resize', this.resizeHandler);
    window.addEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    async fetchData() {
      try {
        const response = await http.get("/hot.json");
        console.log('完整 response 对象:', response);

        let data;
        if (response && response.data) {
          data = response.data;
        } else if (response && typeof response === 'object') {
          data = response;
        } else {
          console.error('无法从 response 中提取数据:', response);
          return;
        }

        console.log('提取的数据:', data);

        const flattenedData = [];
        const traverse = (nodes) => {
          if (Array.isArray(nodes)) {
            nodes.forEach((node) => {
              if (node.value) {
                flattenedData.push({ value: node.value, name: node.name });
              }
              if (node.children) {
                traverse(node.children);
              }
            });
          }
        };

        if (Array.isArray(data)) {
          traverse(data);
        } else {
          console.error('提取的 data 不是数组，数据结构不符合预期:', data);
        }

        this.chartData = flattenedData;
        this.$nextTick(() => {
          this.initChart();
        });
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    },
    initChart() {
      if (this.myChart) {
        this.myChart.dispose();
      }
      const chartDom = this.$refs.chart;
      if (chartDom) {
        this.myChart = echarts.init(chartDom);
        this.updateChart();
      }
    },
    updateChart() {
      const option = {
        title: {
          text: '热销商品的占比',
          left: '20',
          top: '10',
          textStyle: {
            color: "#fff",
            fontSize: 18,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          icon: "circle",
          left: 'center',
          top: 50,
          textStyle: {
            color: "#fff"
          },
          data: this.currentPageData.map(item => item.name)
        },
        series: [
          {
            name: '热销商品占比',
            type: 'pie',
            radius: ['0%','40%'],
            avoidLabelOverlap: true,
           

            label: {
              show: false,
              position: 'outside',
              formatter: '{b}'
            },
            emphasis: {
              label: {
                scale: true,  // 确保启用缩放
                scaleSize: 1.7,
                itemStyle: {
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)',
                },
                show: true,
                fontSize: 14,
                fontWeight: 'bold',
                position: 'outside',
                formatter: '{b}'
              }
            },
            labelLine: {
              show: false
            },
            data: this.currentPageData
          }
        ]
      };

      this.myChart.setOption(option);
    },
    handleKeyDown(event) {
      if (event.key === 'ArrowLeft') {
        this.currentPage = Math.max(0, this.currentPage - 1);
        this.initChart();
      } else if (event.key === 'ArrowRight') {
        this.currentPage = Math.min(this.totalPages - 1, this.currentPage + 1);
        this.initChart();
      }
    },
    resizeHandler() {
      if (this.myChart) {
        this.myChart.resize();
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeHandler);
    window.removeEventListener('keydown', this.handleKeyDown);
    if (this.myChart) {
      this.myChart.dispose();
    }
  }
};
</script>

<style scoped>
.chart-container {
  height: 100%;
  width: 100%;
}

.pagination {
  text-align: center;
  margin-top: 10px;
  color: #fff;
}
</style>